﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 龟兔赛跑的简单实现
{
    public partial class Form1 : Form
    {
        private Image[] images = {Resource1.tuzi, Resource1.wugui };
        private bool isWin = false;
        private bool stopThreads = false;
        public Form1()
        {
            InitializeComponent();

            //关闭跨线程访问，否则出现异常
            CheckForIllegalCrossThreadCalls = false;//设置该属性 为false
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            pictureBox1.Image = images[0];
            pictureBox2.Image = images[1];
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread thread1 = new Thread(TuziRun);
            Thread thread2 = new Thread(WuGuiRun);
            thread1.IsBackground = true;
            thread2.IsBackground = true;
            thread1.Start();
            thread2.Start();
        }

        public void TuziRun()
        {
            Random random = new Random();
            while (!stopThreads)
            {
                int v = random.Next(1, 25);
                Console.WriteLine(pictureBox1.Location.X);
                if (pictureBox1.Location.X >= 600)
                {
                    if (!isWin)
                    {
                        isWin = true;
                        MessageBox.Show("兔子胜利", "比赛结果", MessageBoxButtons.OK);
                        stopThreads = true;//停止线程
                    }
                }
                if (!stopThreads) // 再次检查终止标志
                {
                    pictureBox1.Location = new Point(pictureBox1.Location.X + v, pictureBox1.Location.Y);
                    Thread.Sleep(random.Next(0, 500));
                    
                }
            }
        }
        public void WuGuiRun()
        {
            Random random = new Random();
            while (!stopThreads)
            {
                int v = random.Next(1, 10);
                if (pictureBox2.Location.X >= 600)
                {
                    if(!isWin) 
                    {
                        isWin = true;
                        MessageBox.Show("乌龟胜利", "比赛结果", MessageBoxButtons.OK);
                        stopThreads = true; //停止线程
                    }
                    break;
                }
                if(!stopThreads)
                {
                    pictureBox2.Location = new Point(pictureBox2.Location.X + v, pictureBox2.Location.Y);
                    //乌龟的休息时间
                    Thread.Sleep(random.Next(0, 200));
                }
            }
        }
    }
}
